import React, { useEffect, useState } from 'react';
import { Table, Button, Card, Modal, Form, Input, Checkbox, Space, message, Typography } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Role, Permission } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';
import { mockRoles } from '../../services/mockData';

const { Title } = Typography;

const allPermissions: { key: Permission; label: string }[] = [
  { key: 'dashboard', label: '仪表盘' },
  { key: 'product', label: '商品管理' },
  { key: 'category', label: '分类管理' },
  { key: 'order', label: '订单管理' },
  { key: 'role', label: '角色管理' },
];

const RoleManagement: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    let saved = Storage.get<Role[]>(STORAGE_KEYS.ROLES);
    if (!saved) {
      saved = mockRoles;
    } else {
      // 兼容 localStorage 取出 permissions 为 string[] 的情况
      saved = saved.map(r => ({
        ...r,
        permissions: (r.permissions as string[]).map(p => p as Permission),
      }));
    }
    setRoles(saved);
  }, []);

  const saveRoles = (newRoles: Role[]) => {
    Storage.set(STORAGE_KEYS.ROLES, newRoles);
    setRoles(newRoles);
  };

  const handleAdd = () => {
    setEditingRole(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    form.setFieldsValue(role);
    setModalVisible(true);
  };

  const handleDelete = (roleId: string) => {
    const newRoles = roles.filter(r => r.id !== roleId);
    saveRoles(newRoles);
    message.success('删除成功');
  };

  const handleSubmit = (values: any) => {
    if (editingRole) {
      // 编辑
      const newRoles = roles.map(r => r.id === editingRole.id ? { ...editingRole, ...values } : r);
      saveRoles(newRoles);
      message.success('更新成功');
    } else {
      // 新增
      const newRole: Role = {
        id: Date.now().toString(),
        ...values,
      };
      saveRoles([...roles, newRole]);
      message.success('添加成功');
    }
    setModalVisible(false);
  };

  const columns = [
    { title: '角色名称', dataIndex: 'name', key: 'name' },
    { title: '权限', dataIndex: 'permissions', key: 'permissions', render: (perms: Permission[]) => perms.map(p => allPermissions.find(ap => ap.key === p)?.label).join('，') },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: Role) => (
        <Space size="small">
          <Button icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Button icon={<DeleteOutlined />} size="small" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Title level={2}>角色管理</Title>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>添加角色</Button>
      </div>
      <Card>
        <Table columns={columns} dataSource={roles} rowKey="id" pagination={false} />
      </Card>
      <Modal
        title={editingRole ? '编辑角色' : '添加角色'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit} initialValues={{ permissions: [] }}>
          <Form.Item name="name" label="角色名称" rules={[{ required: true, message: '请输入角色名称' }]}>
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item name="permissions" label="权限" rules={[{ required: true, message: '请选择权限' }]}> 
            <Checkbox.Group style={{ width: '100%' }}>
              <Space direction="vertical">
                {allPermissions.map(p => (
                  <Checkbox key={p.key} value={p.key}>{p.label}</Checkbox>
                ))}
              </Space>
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleManagement;
